//
// Copyright (C) 2008 Jackson Harper (jackson@ximian.com)

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
//

using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;

using MySql.Data.MySqlClient;

namespace Grr.Model {

	[Serializable]
	public class Tag : DbEntity
	{
		private long instances;

		// For cereal
		public Tag() { }

		public Tag (string name) : base (name)
		{
		}

		public long Instances
		{
			get { return instances; }
			set { instances = value; }
		}

		public List<Tag> GetPopularTags ()
		{
			using (MySqlConnection rcon = OpenReadConnection ()) {
				MySqlCommand qcmd = new MySqlCommand ("select Tags.name, COUNT(tag_map.id) FROM Tags JOIN tag_map ON Tags.id = tag_map.tag_id GROUP BY Tags.name", rcon);

				MySqlDataReader reader = qcmd.ExecuteReader ();

				List<Tag> res = new List<Tag> ();
				while (reader.Read ()) {
					Tag t = new Tag (reader.GetString ("name"));
					t.instances = reader.GetInt64 ("COUNT(tag_map.id)");

					res.Add (t);
				}
				return res;
			}
		}


		public static long GetTagId(string name)
		{
			using (MySqlConnection rcon = OpenReadConnection ()) {
				MySqlCommand qcmd = new MySqlCommand ("select id FROM Tags WHERE name = ?name", rcon);
				qcmd.Parameters.Add ("?name", MySqlDbType.VarChar, 100).Value = name;

				long res;
				MySqlDataReader reader = qcmd.ExecuteReader ();

				if (!reader.Read ()) {
					using (MySqlConnection rwcon = OpenReadWriteConnection ()) {
						MySqlCommand icmd = new MySqlCommand("INSERT INTO Tags (name) VALUES (?name)", rwcon);
						icmd.Parameters.Add ("?name", MySqlDbType.VarChar, 100).Value = name;

						icmd.ExecuteNonQuery ();

						qcmd = new MySqlCommand ("SELECT LAST_INSERT_ID()", rwcon);
						res = (long)qcmd.ExecuteScalar ();
						return res;
					}
				}
				res = reader.GetInt64 ("id");
				return res;
			}
		}
	}
}
